#include <fuquOS/number.h>

// 将整数转换为十六进制字符串
void itoa_hex(u32 num, char *buf)
{
  int i = 0;
  if (num == 0)
  {
    buf[i++] = '0';
  }
  else
  {
    while (num)
    {
      buf[i++] = hex_chars[num & 0xF];
      num >>= 4;
    }
  }
  buf[i] = '\0';
  // 反转字符串
  int j = 0;
  int k = i - 1;
  while (j < k)
  {
    char temp = buf[j];
    buf[j] = buf[k];
    buf[k] = temp;
    j++;
    k--;
  }
}

// 将整数转换为十进制字符串
void itoa_dec(u32 num, char *buf)
{
  int i = 0;
  if (num == 0)
  {
    buf[i++] = '0';
  }
  else
  {
    while (num)
    {
      buf[i++] = '0' + (num % 10);
      num /= 10;
    }
  }
  buf[i] = '\0';
  // 反转字符串
  int j = 0;
  int k = i - 1;
  while (j < k)
  {
    char temp = buf[j];
    buf[j] = buf[k];
    buf[k] = temp;
    j++;
    k--;
  }
}

void itoa_hex64(u64 value, char *buf)
{
  int i = 0;

  if (value == 0)
  {
    buf[i++] = '0';
  }
  else
  {
    int start = 0;
    for (int shift = 60; shift >= 0; shift -= 4)
    {
      char hex_digit = (value >> shift) & 0xF;
      if (hex_digit != 0 || start)
      { // 去除前导 0
        buf[i++] = hex_chars[hex_digit];
        start = 1;
      }
    }
  }
  buf[i] = '\0';
}
